<template>
  <div class="addUser">
    <!-- 新增商户 -->
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <!-- 软件版本 -->
      <el-form-item class="filtrate" label="软件版本" size="small" prop="sv_versionname">
        <el-radio-group v-model="ruleForm.sv_versionname" size="mini" @change="handleSelectVersion">
          <el-radio-button
            v-for="(item, index) in versions"
            :class="item.sv_version_code == ruleForm.sv_version_code ? 'is-active' : ''"
            :key="index"
            :value="item.sv_versionname"
            :label="item"
          >{{item.sv_versionname}}</el-radio-button>
        </el-radio-group>
        <div style="color: red;font-size: 12px;width: 85%">
          {{combo}}
          <el-tooltip class="item" effect="dark" :content="remarks" placement="top">
            <i style="color: #30c17b;font-size: 20px;cursor: pointer" class="iconfont iconwenhao1"></i>
          </el-tooltip>
        </div>
        <div class="buyPrice">
          <div v-if="ruleForm.sv_versionid == 3">
            购买：
            <el-input-number v-model="ruleForm.order_count" @change="handleChangeYear" :min="1"></el-input-number>/年
          </div>
          <div v-if="ruleForm.sv_versionid == 5">
            购买：
            <el-input-number v-model="ruleForm.buyshopnumber" @change="handleChangeNum" :min="1"></el-input-number>/店
          </div>
          <div v-if="ruleForm.sv_versionid == 3">
            分店数：
            <el-input-number v-model="ruleForm.buyshopnumber" @change="handleChangeNum" :min="0"></el-input-number>
          </div>
        </div>
      </el-form-item>
      <!-- 行业类型 -->
      <el-form-item label="选择时限" size="small" prop="sv_versionid">
        <el-radio-group v-model="ruleForm.sv_versionid" @change="handleChangeTime">
          <el-radio-button
            :disabled="ruleForm.sv_version_type==1||!timeshow?true:false"
            label="3"
            :class="ruleForm.sv_version_type==2 ? 'chooseColor': ''"
          >年</el-radio-button>
          <el-radio-button
            :disabled="ruleForm.sv_version_type==2||!timeshow?true:false"
            label="5"
            :class="ruleForm.sv_version_type==1 ? 'chooseColor': ''"
          >终身</el-radio-button>
        </el-radio-group>
        <span style="margin-left: 20px">
          价格：
          <span style="color: red;font-size: 18px">{{ruleForm.sv_versionsaleprice}}</span>
          <del style="color: #ccc">原价：{{ruleForm.sv_versionorigprice}}</del>
          <strong style="margin-left: 20px;font-size: 18px">总价：{{ruleForm.sv_do_price}}</strong>
        </span>
      </el-form-item>
      <el-form-item label="行业类型" size="small" prop="sv_us_industrytype">
        <el-select size="medium" v-model="ruleForm.sv_us_industrytype" placeholder="请选择行业">
          <el-option
            v-for="(item, index) in business"
            :key="index"
            :label="item.sv_uit_name"
            :value="item.industrytype_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 店铺简称 -->
      <el-form-item label="店铺简称" size="small" prop="sv_us_shortname">
        <el-input size="medium" v-model="ruleForm.sv_us_shortname" placeholder="请输入店铺简称"></el-input>
      </el-form-item>
      <!-- 店铺名称 -->
      <el-form-item label="店铺名称" size="small" prop="sv_us_name">
        <el-input size="medium" v-model="ruleForm.sv_us_name" placeholder="请输入店铺名称"></el-input>
      </el-form-item>
      <!-- 商户姓名 -->
      <el-form-item label="商户姓名" size="small" prop="sv_ul_name">
        <el-input size="medium" v-model="ruleForm.sv_ul_name" placeholder="请输入商户姓名" clearable></el-input>
      </el-form-item>
      <!-- 商户手机号 -->
      <el-form-item label="商户账号" size="small" type="number" prop="sv_ul_mobile">
        <el-input size="medium" v-model="ruleForm.sv_ul_mobile" placeholder="请输入商户手机/账号"></el-input>
      </el-form-item>
      <!-- 设置密码 -->
      <el-form-item label="设置密码" size="small" prop="sv_ul_loginpwd">
        <el-input size="medium" v-model="ruleForm.sv_ul_loginpwd" placeholder="请输入密码" show-password></el-input>
      </el-form-item>
      <!-- 店铺电话 -->
      <el-form-item label="店铺电话" size="small">
        <el-input size="medium" v-model="ruleForm.sv_us_phone" placeholder="请输入店铺电话"></el-input>
      </el-form-item>
      <!-- 推荐人 -->
      <el-form-item label="推荐人" size="small">
        <el-input size="medium" v-model="ruleForm.sv_us_reference" placeholder="请输入推荐人"></el-input>
      </el-form-item>
      <!-- 经理/客服 -->
      <el-form-item label="经理/客服" size="small">
        <el-select size="medium" v-model="ruleForm.sv_openshop_person" placeholder="请选择经理/客服">
          <el-option
            v-for="(item, index) in userData"
            :key="index"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 店铺地址 -->
      <el-form-item class="adressSelect" label="店铺地址" size="small">
        <el-cascader
          expand-trigger="hover"
          :options="options"
          v-model="selectedOptions"
          @change="handleChange"
          placeholder="请选择地址"
          size="small"
        ></el-cascader>
        <el-input
          size="medium"
          v-model="ruleForm.sv_us_address"
          placeholder="请输入店铺地址"
          class="detailAdress"
        ></el-input>
      </el-form-item>
      <!-- 支付配置 -->
      <el-form-item v-if="isShow" label="支付配置" size="small">
        <el-select size="medium" v-model="ruleForm.dec_payment_method" placeholder="请选择支付配置">
          <el-option label="官方支付通道" value="0"></el-option>
          <el-option
            v-for="(item, index) in channels"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-input
          size="medium"
          style="margin-top: 10px;margin-bottom: 10px"
          v-model="mercId"
          :placeholder="ruleForm.dec_payment_method == 12 ? '请输入商户号':'请输入收款Key'"
        ></el-input>
        <el-input
          v-if="ruleForm.dec_payment_method == 12"
          size="medium"
          v-model="signKey"
          placeholder="请输入终端号"
        ></el-input>
        <el-input v-else size="medium" v-model="signKey" placeholder="请输入加密Key"></el-input>
      </el-form-item>
      <!-- 套餐总代币 -->
      <el-form-item label="套餐总代币" size="small">
        <el-input size="medium" v-model="ruleForm.sv_do_price" disabled></el-input>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item size="large">
        <el-button
          style="margin-left: 15%;padding: 8px 30px"
          type="primary"
          @click="onSubmit('ruleForm')"
        >完成</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { regionData } from "element-china-area-data";
import { mapState } from "vuex"; //注册state
export function checkSpecificKey(str) {
  var specialKey =
    "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'";
  for (var i = 0; i < str.length; i++) {
    if (specialKey.indexOf(str.substr(i, 1)) != -1) {
      return false;
    }
  }
  return true;
}
export default {
  data() {
    // 验证特殊字符
    var validateInput = (rule, value, callback) => {
      if (!checkSpecificKey(value)) {
        callback(new Error("Special symbols are not supported"));
      } else {
        callback();
      }
    };
    // const patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im;
    // 验证数字字母和特殊字符
    const pwdPatrn = /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、0-9A-Za-z]{6,}$/;
    return {
      ruleForm: {
        sv_versionname: "", // 软件版本
        sv_versionid: "",
        sv_versionsaleprice: "", // 单价
        sv_do_originalprice: "", // 原价
        order_count: 1, // 年份
        buyshopnumber: 1, // 数量
        sv_version_code: "", // 版本编号
        gid: "", // 版本唯一标识
        is_version_pack: false, // 是否购买套餐
        sv_us_industrytype: "", // 行业类型
        sv_ul_name: "", // 客户名称
        sv_ul_mobile: "", // 客户手机
        sv_ul_loginpwd: "", // 密码
        sv_us_shortname: "", // 店铺简称
        sv_us_name: "", // 店铺名称
        sv_us_phone: "", // 店铺电话
        sv_us_reference: "", // 推荐人
        sv_openshop_person: "", // 经理/客服
        sv_us_province: 0, // 省份
        sv_us_city: 0, // 市
        sv_us_district: 0, // 区
        sv_us_address: "", // 店铺地址
        sv_do_price: "", // 购买总价格
        dec_payment_method: "0", // 支付方式
        dec_payment_config: {} // 支付配置
      },
      rules: {
        sv_versionname: [
          { required: true, message: "请选择软件版本", trigger: "change" }
        ],
        sv_versionid: [
          { required: true, message: "请选择购买时限", trigger: "change" }
        ],
        sv_us_industrytype: [
          { required: true, message: "请选择行业类型", trigger: "change" }
        ],
        sv_us_shortname: [
          { required: true, message: "请输入店铺简称", trigger: "blur" },
          {
            min: 1,
            max: 8,
            message: "店铺简称长度不得超过8字符",
            trigger: "blur"
          },
          {
            validator: validateInput,
            message: "店铺简称请勿输入特殊字符",
            trigger: "blur"
          }
        ],
        sv_us_name: [
          { required: true, message: "请输入店铺名称", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "店铺名称长度不得超过30字符",
            trigger: "blur"
          },
          {
            validator: validateInput,
            message: "店铺名称请勿输入特殊字符",
            trigger: "blur"
          }
        ],
        sv_ul_name: [
          { required: true, message: "请输入店铺名称", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "商户姓名长度不得超过20个字符",
            trigger: "blur"
          }
        ],
        sv_ul_mobile: [
          {
            required: true,
            pattern: /^[0,1,6,8][013456789]\d{8,9}$/,
            message: "手机号格式不对",
            trigger: "blur"
          }
        ],
        sv_ul_loginpwd: [
          {
            required: true,
            pattern: pwdPatrn,
            message: "密码格式错误",
            trigger: "blur"
          }
        ]
      },
      buyfortime: "", // 0 年，1 终身
      timeshow: false,
      chooseid: 3,
      channels: [], // 支付通道
      mercId: "", // 付款key
      signKey: "", // 加密key
      isShow: true, // 根据id隐藏支付配置
      // 这个是版本号的数据
      versions: [],
      versionsCodeList: [],
      combo: "", // 套餐信息
      remarks: "版本功能说明", // 版本说明
      // 这个是行业类型
      business: [],
      // 这个是客服/经理
      userData: [],
      // 地址级联数据
      options: regionData,
      selectedOptions: [],
      // 身份令牌
      myToken: ""
    };
  },
  computed: {
    // 引入权限页面
    ...mapState(["userId"]),
    ...mapState(["payEnable"])
  },
  methods: {
    // 初始化函数
    init() {
      // 获取令牌
      this.myToken = sessionStorage.getItem("myToken");
      if (!this.payEnable) {
        // 隐藏权限不足页面
        this.isShow = false;
      }
      if (this.userId == 114) {
        this.channels = [
          { name: "酷享灵风支付通道", id: 6 },
          { name: "酷享灵风支付V3.0通道", id: 7 }
        ];
      } else if (this.userId == 252 || this.userId == 120) {
        this.channels = [{ name: "HaiPay", id: 10 }];
      } else if (this.userId == 120 || this.userId == 121) {
        this.channels = [{ name: "QPay", id: 12 }];
      }
      // 版本号信息
      this.$api
        .accordingToIdGetVersion("1,3,12", true, this.myToken)
        .then(res => {
          this.versions = res.list.map(v => {
            return {
              ...v
            };
          });
        });
      this.$api.getIndustryData(this.myToken).then(res => {
        this.business = res.map(v => {
          return {
            ...v
          };
        });
      });
      // 获取客服/经理
      this.$api.getManagerData(this.myToken).then(res => {
        const { dataList, total } = res;
        this.total = total;
        if (dataList) {
          this.userData = dataList.map(v => {
            return {
              name: v.sv_d_user_name
            };
          });
        }
      });
    },
    // 选择版本
    handleSelectVersion(val) {
      // console.log(val);
      this.ruleForm.buyshopnumber = 1;
      this.ruleForm.order_count = 1;
      this.ruleForm.sv_versionsaleprice = "";
      this.ruleForm.sv_versionorigprice = "";
      this.ruleForm.sv_do_price = "";
      this.combo = "";
      this.timeshow = true;
      this.remarks = "版本功能说明";
      this.ruleForm.sv_versionid = "";
      this.ruleForm.sv_version_type = val.sv_version_type;
      // 获取当前编号的版本
      this.getCurrentVersion(val.sv_version_code);
      // 显示购买年限和终身的选择按钮
      if (val.sv_versionid == 1) {
        this.timeshow = false;
        this.ruleForm.sv_versionid = 1;
        this.ruleForm.gid = val.gid;
        this.ruleForm.sv_versionsaleprice = "0";
        this.ruleForm.sv_do_originalprice = "0";
        this.ruleForm.sv_versionname = "免费版";
        this.ruleForm.sv_versionorigprice = "0";
        this.ruleForm.sv_do_price = "0";
      }
      if (val.sv_versionid == 5 || val.sv_versionid == 12) {
        this.manualSettingSection(val);
      }
    },
    // 手动设置部分
    manualSettingSection(val) {
      this.combo = val.package_remarks;
      this.remarks = val.sv_remarks;
      this.ruleForm.sv_versionsaleprice = val.sv_versionsaleprice;
      this.ruleForm.sv_do_originalprice = val.sv_versionorigprice;
      this.ruleForm.sv_do_price = val.sv_versionsaleprice;
      this.ruleForm.sv_versionname = val.sv_versionname;
      this.ruleForm.sv_versionid = val.sv_versionid;
      this.ruleForm.is_version_pack = val.is_version_pack;
      this.ruleForm.gid = val.gid;
      this.ruleForm.sv_versionorigprice = val.sv_versionorigprice;
    },
    // 获取当前编号的版本
    /**
     * @code 版本编号
     * @gid 版本唯一标识
     **/
    getCurrentVersion(code, gid) {
      this.$api
        .accordingToVersionTypeGetVersion(code || "", gid || "", this.myToken)
        .then(res => {
          const { list } = res;
          var val = list[0];
          this.ruleForm.sv_version_code = val.sv_version_code;
          if (code == "Basics_Version_code") {
            this.versions[0].sv_versionname = val.sv_versionname;
          }
          if (gid == "c84ede74-0565-4349-d534-62e9789867b1") {
            this.versions[0].sv_versionname = val.sv_versionname;
          }
          if (gid == "4850e0b5-2be8-6822-f9f9-dc099d83bbb5") {
            this.versions[0].sv_versionname = val.sv_versionname;
          }
          if (code) {
            this.versionsCodeList = list.map(v => {
              return {
                gid: v.gid
              };
            });
          } else {
            this.combo = val.package_remarks;
            this.remarks = val.sv_remarks;
            this.ruleForm.sv_versionsaleprice = val.sv_versionsaleprice;
            this.ruleForm.sv_do_originalprice = val.sv_versionorigprice;
            this.ruleForm.sv_versionname = val.sv_versionname;
            this.ruleForm.sv_versionid = val.sv_versionid;
            this.ruleForm.is_version_pack = val.is_version_pack;
            this.ruleForm.gid = val.gid;
            this.ruleForm.sv_versionorigprice = val.sv_versionorigprice;
            if (this.ruleForm.sv_versionid == 3) {
              this.ruleForm.buyshopnumber = 0;
              this.ruleForm.sv_do_price =
                this.ruleForm.sv_versionsaleprice *
                this.ruleForm.order_count *
                (this.ruleForm.buyshopnumber + 1);
            } else {
              this.ruleForm.buyshopnumber = 1;
              this.ruleForm.sv_do_price =
                this.ruleForm.sv_versionsaleprice *
                this.ruleForm.order_count *
                this.ruleForm.buyshopnumber;
            }
          }
        });
    },
    // 选择版本购买时长
    handleChangeTime(val) {
      // 判断是按年0还是按终身1
      if (val == 3) {
        // 获取当前编号的版本
        this.getCurrentVersion("", this.versionsCodeList[0].gid);
      } else {
        // 获取当前编号的版本
        if (this.versionsCodeList[1]) {
          this.getCurrentVersion("", this.versionsCodeList[1].gid);
        } else {
          this.getCurrentVersion("", this.versionsCodeList[0].gid);
        }
      }
    },
    // 选择购买年份
    handleChangeYear(val) {
      this.ruleForm.order_count = val;
      if (this.ruleForm.sv_versionid == 3) {
        this.ruleForm.sv_do_price =
          this.ruleForm.sv_versionsaleprice *
          val *
          (this.ruleForm.buyshopnumber + 1);
      } else {
        this.ruleForm.sv_do_price =
          this.ruleForm.sv_versionsaleprice * val * this.ruleForm.buyshopnumber;
      }
    },
    // 选择购买数量
    handleChangeNum(val) {
      this.ruleForm.buyshopnumber = val;
      if (this.ruleForm.sv_versionid == 3) {
        this.ruleForm.sv_do_price =
          this.ruleForm.sv_versionsaleprice *
          (val + 1) *
          this.ruleForm.order_count;
      } else {
        this.ruleForm.sv_do_price = this.ruleForm.sv_versionsaleprice * val;
      }
    },
    // 提交表单
    onSubmit(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.ruleForm.dec_payment_method == 12) {
            this.ruleForm.dec_payment_config = JSON.stringify({
              orgNo: "0",
              trmNo: this.signKey,
              txamt: "",
              mercId: this.mercId,
              signKey: "",
              payChannel: "",
              outOrderNum: "",
              ShopNo: this.signKey,
              ShopName: "我的店铺"
            });
          } else {
            this.ruleForm.dec_payment_config = JSON.stringify({
              orgNo: "0",
              trmNo: "0",
              txamt: "",
              mercId: this.mercId,
              signKey: this.signKey,
              payChannel: "",
              outOrderNum: ""
            });
          }
          // 提交数据
          this.$api.SaveTheChanges(this.ruleForm, this.myToken).then(res => {
            const { errmsg, succeed } = res;
            if (succeed) {
              this.$message({
                message: "新增成功",
                type: "success"
              });
              this.$router.push({
                path: "myMerchant",
                query: {
                  x: 2
                }
              });
            } else {
              this.$message.error(errmsg);
            }
          });
        } else {
          return false;
        }
      });
    },
    // 级联选择变化的方法
    handleChange(val) {
      this.ruleForm.sv_us_province = val[0];
      this.ruleForm.sv_us_city = val[1];
      this.ruleForm.sv_us_district = val[2];
    }
  },
  mounted() {
    // 初始化函数
    this.init();
  }
};
</script>

<style scoped lang="less">
@deep: ~">>>";
.addUser {
  // 地址级联的样式
  .adressOpation {
    width: 95px;
  }
  .detailAdress {
    margin-top: 10px;
  }
  .buyPrice {
    width: 500px;
    display: flex;
    margin-top: 10px;
    justify-content: space-between;
  }
  .filtrate {
    margin: 20px 0;
    margin-top: 0;
    background-color: #fff;
    width: 700px;
    .el-radio-button {
      margin-right: 10px;
      margin-bottom: 10px;
      width: 90px;
      line-height: 25px;
      overflow: hidden;
    }
  }
  // 按钮组的内容
  .filtrate @{deep} .el-radio-button__inner {
    width: 90px;
    border: 1px solid #f1f1f1;
    background-color: #f1f1f1;
    color: #626366;
    font-size: 14px;
    line-height: 25px;
  }
  // 按钮组选中内容
  .filtrate @{deep} .is-active .el-radio-button__inner {
    background-color: #439fff;
    border: 1px solid #439fff;
    box-shadow: unset;
    color: #fff;
    border-radius: 4px;
    line-height: 25px;
  }
}
.addUser @{deep} .demo-ruleForm {
  background-color: #fff;
  padding: 30px 30%;
  box-sizing: border-box;
}
// 修改输入框样式
.addUser @{deep} .el-input {
  width: 500px;
}
// 输入框右边的小提示
.addUser @{deep} .el-upload-list--picture {
  width: 500px;
}
// 表单样式
.addUser @{deep} .el-form {
  padding: 30px 25%;
  box-sizing: border-box;
}
// 总金额
.addUser @{deep} .is-disabled .el-input__inner {
  color: red;
  font-weight: 600;
}
// 输入框的宽度
.addUser @{deep} .el-input__inner {
  width: 500px;
}
.adressOpation @{deep} .el-input__inner {
  width: 95px;
}
.buyPrice @{deep} .el-input__inner {
  width: 130px;
}
.buyPrice @{deep} .el-input {
  width: 130px;
}
.chooseColor {
  @{deep} .el-radio-button__inner {
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
    box-shadow: -1px 0 0 0 #409eff;
  }
}
</style>